﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jbe.TestSuite.Infrastructure.Interface;
using System.Windows.Media;
using System.ComponentModel;
using System.IO;
using Microsoft.Practices.Composite.Presentation.Commands;
using Jbe.TestSuite.CodeEditor.Domain;
using Jbe.Composite.Extensions;
using System.Windows;
using System.Reflection;
using System.Windows.Documents;
using ICSharpCode.AvalonEdit.Document;
using Jbe.TestSuite.CodeEditor.Properties;

namespace Jbe.TestSuite.CodeEditor.Applications
{
    internal class CodeEditorPresentationModel : PresentationModel<ICodeEditorView>, IHeaderInfoProvider
    {
        private static readonly PropertyInfo HeaderInfoProperty = TypeManager.GetProperty<CodeEditorPresentationModel>(x => x.HeaderInfo);


        private readonly CodeDocument document;


        public CodeEditorPresentationModel(ICodeEditorView view, CodeDocument document)
            : base(view)
        {
            this.document = document;
            PropertyChangedEventManager.AddListener(document, this, "");
        }


        public CodeDocument Document { get { return document; } }

        public string HeaderInfo
        {
            get { return Path.GetFileName(document.FileName) ?? string.Format(Resources.DocumentTemplate, 1); }
        }

        public ImageSource HeaderIcon
        {
            get { return ResourceService.CreateBitmapSource(Resources.TextDoc.ToBitmap()); }
        }


        protected override void ReceiveWeakEvent(Type managerType, object sender, EventArgs e, ref bool handled)
        {
            base.ReceiveWeakEvent(managerType, sender, e, ref handled);

            if (managerType == typeof(PropertyChangedEventManager) && sender == document)
            {
                DocumentPropertyChanged(sender, (PropertyChangedEventArgs)e);
                handled = true;
            }
        }

        private void DocumentPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "FileName") { RaisePropertyChanged(HeaderInfoProperty); }
        }


        #region TextContent
        /// <summary>
        /// This property wraps the document class provided by AvalonEdit. The actual text is inside
        /// the document and can be accessed at save, load or other processing times.
        /// 
        /// The Text property itself cannot be bound in AvalonEdit since binding this would result
        /// in updating the text (via binding) each time a user enters a key on the keyboard
        /// (which would be a design error resulting in huge performance problems)
        /// </summary>
        public TextDocument CodeDocument
        {
            get { return document.Content; }
        }
        #endregion
    }
}
